import cv2  
import numpy as np  
import matplotlib.pyplot as plt  

cap = cv2.VideoCapture(0)
ret = cap.set(3, 640)  # 设置帧宽
ret = cap.set(4, 480)  # 设置帧高
font = cv2.FONT_HERSHEY_SIMPLEX  # 设置字体样式
 
if cap.isOpened() is True:  # 检查摄像头是否正常启动
    while(True):
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 转换为灰色通道
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)  # 转换为HSV空间
  
        plt.subplot(121),plt.imshow(gray,'gray')  
        plt.xticks([]),plt.yticks([])  

        circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,600,param1=90,param2=70,minRadius=5,maxRadius=300)  
        if circles is not None:  # 如果识别出圆
            for circle in circles[0]:
                #  获取圆的坐标与半径
                x = int(circle[0])
                y = int(circle[1])
                r = int(circle[2])
                cv2.circle(frame, (x, y), r, (0, 0, 255), 3)  # 标记圆
                cv2.circle(frame, (x, y), 3, (255, 255, 0), -1)  # 标记圆心
                text = 'x:  '+str(x)+' y:  '+str(y)
                cv2.putText(frame, text, (10, 30), font, 1, (0, 255, 0), 2, cv2.LINE_AA, 0)  # 显示圆心位置
        else:
            # 如果识别不出，显示圆心不存在
            cv2.putText(frame, 'x: None y: None', (10, 30), font, 1, (0, 255, 0), 2, cv2.LINE_AA, 0)
        cv2.imshow('frame', frame)
        k = cv2.waitKey(5) & 0xFF
        if k == 27:
            break




# cap = cv2.VideoCapture(0)
# ret = cap.set(3, 640)  # 设置帧宽
# ret = cap.set(4, 480)  # 设置帧高
 
# if cap.isOpened() is True:  # 检查摄像头是否正常启动
#     while(True):
#         ret, frame = cap.read()
#         gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 转换为灰色通道
#         hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)  # 转换为HSV空间
  
#         plt.subplot(121),plt.imshow(gray,'gray')  
#         plt.xticks([]),plt.yticks([])  

#         circles1 = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,600,param1=100,param2=30,minRadius=80,maxRadius=97)  
#         circles = circles1[0,:,:]  
#         circles = np.uint16(np.around(circles))  
#         for i in circles[:]:   
#             cv2.circle(frame,(i[0],i[1]),i[2],(255,0,0),5)  
#             cv2.circle(frame,(i[0],i[1]),2,(255,0,255),10)  
#             cv2.rectangle(frame,(i[0]-i[2],i[1]+i[2]),(i[0]+i[2],i[1]-i[2]),(255,255,0),5)  

#         print("圆心坐标",i[0],i[1])  
#         cv2.imshow('frame', frame)